<template>
  <div class="register-content">

    <div class="weui-cells weui-cells_form">
      <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">姓名</label></div>
        <div class="weui-cell__bd">
          <input class="weui-input" type="text" placeholder="请输入会员姓名" v-model="username" value=""/>
        </div>
      </div>
      <div class="weui-cell weui-cell_select weui-cell_select-after" style="padding: 0 0 0 .4rem;">
        <div class="weui-cell__hd">
          <label class="weui-label">性别</label>
        </div>
        <div class="weui-cell__bd">
          <select class="weui-select" name="select2" style="color: #999999;" v-model="sexId">
            <option value="0">请选择性别</option>
            <option value="1">男</option>
            <option value="2">女</option>
          </select>
        </div>
      </div>
      <div class="weui-cell weui-cell_select-after">
        <div class="weui-cell__hd"><label for="" class="weui-label">生日</label></div>
        <div class="weui-cell__bd">
          <input class="weui-input" style="color: #999999;" type="date"
                 placeholder="请输入会员生日" v-model="birthday"/>
        </div>
      </div>
    </div>
    <div class="form weui-cells weui-cells_form" v-if="verifyMobile">
      <div class="weui-cell weui-cell_vcode mobile" style="padding: 0 0 0 .4rem">
        <div class="weui-cell__hd">
          <label class="weui-label">手机号</label>
        </div>
        <div class="weui-cell__bd">
          <input class="weui-input" type="tel" placeholder="请输入手机号" v-model="mobile">
        </div>
        <div class="weui-cell__ft">
          <a href="javascript:;" class="weui-vcode-btn" v-on:click="getCode" v-if="showGetCodeBtn"
             style="font-size: .373rem;color: #ff6600;">获取验证码</a>
          <a href="javascript:;" class="weui-vcode-btn" v-else
             style="font-size: .373rem;color: #dedede;">重新发送({{getCodeBtnText}})</a>
        </div>
      </div>
      <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">验证码</label></div>
        <div class="weui-cell__bd">
          <input class="weui-input" type="text" pattern="[0-9]*" placeholder="请输入短信中的验证码" v-model="code"/>
        </div>
      </div>
    </div>
    <div class="form weui-cells weui-cells_form" v-else>
      <div class="weui-cell">
        <div class="weui-cell__hd"><label class="weui-label">手机号</label></div>
        <div class="weui-cell__bd">
          <input class="weui-input" type="tel" pattern="[0-9]*" placeholder="请输入手机号" v-model="mobile"/>
        </div>
      </div>
    </div>
    <div class="weui-cells__title" style="text-align: center;margin-top: 1.173rem;">资料一旦提交无法修改</div>
    <div class="button-sp-area">
      <a href="javascript:;" class="register weui-btn weui-btn_plain-primary" v-on:click="register">注册</a>
    </div>

    <transition enter-active-class="bounceInDown" leave-active-class="bounceOutUp">
      <div id="dialog1" v-show="showAlertToBind" class="animated">
        <div class="weui-dialog weui-skin_android">
          <div class="weui-dialog__hd"><strong class="weui-dialog__title"
                                               style="font-size: .54rem;color: #333">提示</strong></div>
          <div class="weui-dialog__bd" style="font-size: .427rem; color: #666">{{alertText}}</div>
          <div class="weui-dialog__ft">
            <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default" v-on:click="cancelAlert">取消</a>
            <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" v-on:click="bindMember"
               style="color: #ff6600">{{alertBtn}}</a>
          </div>
        </div>
      </div>
    </transition>

    <div id="dialog2" v-show="showAlert">
      <div class="weui-mask"></div>
      <div class="weui-dialog weui-skin_android">
        <div class="weui-dialog__hd"><strong class="weui-dialog__title"
                                             style="font-size: 0.533rem;color: #333">提示</strong>
        </div>
        <div class="weui-dialog__bd" style="font-size: 0.426667rem; color: #666">{{alertText}}</div>
        <div class="weui-dialog__ft">
          <a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary" style="color: #ff6600"
             v-on:click="hideAlert">我知道了</a>
        </div>
      </div>
    </div>

    <loading :show="showLoading" :text="showLoadingText"></loading>
    <toast v-model="showToast" width="5rem" :type="toastType" :time="800" :text="toastText"></toast>

  </div>
</template>
<script>

  import {Loading, Toast} from 'vux'

  import {utils} from './../common/utils/utils'

  const enumerations = require('./../common/utils/enumerations')
  const common = require('./../common/utils/common')
  const error = require('./../common/utils/error')

  export default {
    components: {
      Loading,
      Toast
    },
    data() {
      return {
        mchCodeByUrl: common.getUrlParam('mchCode'),
        openidByUrl: common.getUrlParam('openid'),
        cacheMchCode: localStorage.getItem('mchCode'),
        cacheMchType: localStorage.getItem('type'),
        openid: localStorage.getItem('openid'),

        getCodeBtnText: '获取验证码',
        showGetCodeBtn: true,

        verifyMobile: false,
        verifyMobileType: '',

        mobile: '',
        username: '',
        sexId: 1,
        birthday: '1990-01-01',
        code: '',

        showAlert: false,
        showAlertToBind: false,
        alertText: '该手机号已注册，请直接绑定会员',
        alertBtn: '绑定会员',

        showMask: false,
        showLoading: false,
        showLoadingText: '',
        showToast: false,
        toastType: 'cancel',
        toastText: '',
      }
    },
    beforeCreate() {
      document.title = '注册会员'
    },
    async created() {
      const _this = this

      //todo 第一步把error抛出
      if (common.isEmptyString(this.mchCodeByUrl)
        && common.isEmptyString(this.cacheMchCode)) {
        //todo 跳error
        _this.$router.push({
          path: 'error',
          params: ''
        })
      }

      if (!common.isEmptyString(this.mchCodeByUrl)
        && this.mchCodeByUrl !== this.cacheMchCode) {

        this.cacheMchCode = this.mchCodeByUrl;
        this.cacheMchType = "";
        this.openid = "";
        //清除缓存
        localStorage.setItem('mchCode', this.mchCodeByUrl)
        localStorage.setItem('type', '')
        localStorage.setItem('openid', '')
        localStorage.setItem('payOpenid', '')

      }

      const mchTypeRes = await utils.getMchType(this.cacheMchCode, _this);

      if (!mchTypeRes.valid) {
        //清除缓存
        localStorage.setItem('mchCode', this.mchCodeByUrl)
        localStorage.setItem('type', '')
        localStorage.setItem('openid', '')
        localStorage.setItem('payOpenid', '')

      } else {

        this.cacheMchType = mchTypeRes.info.type
        localStorage.setItem('type', mchTypeRes.info.type)
        this.verifyMobileType = mchTypeRes.info.verify_mobile
      }

      //如果返回type为空则错误
      if (common.isEmptyString(this.cacheMchType)) {
        _this.$router.push({
          path: 'error',
          params: ''
        })
      }

      if (this.verifyMobileType == enumerations.verifyMobile.yes.key) {
        _this.verifyMobile = true
      } else {
        _this.verifyMobile = false
      }

      if(this.cacheMchType !== enumerations.isNeedGetOauth.yes.key) {
        if(common.isEmptyString(this.openidByUrl)) {
          _this.$router.push({
            path: 'error',
            params: ''
          })
        }
      }

      if (common.isEmptyString(this.openid)
        && common.isEmptyString(this.openidByUrl)) {
        // 授权
        utils.getOauth(this.cacheMchCode, _this)

      } else if (!common.isEmptyString(this.openidByUrl)) {
        this.openid = this.openidByUrl
        localStorage.setItem('openid', this.openidByUrl)
      } else {

        const result = await utils.checkMbInfo(_this)

        if (result["valid"]) {

          const checkMbInfo = result["info"]

          _this.username = checkMbInfo["user_name"]
          if (checkMbInfo["exist_mb"]) {

            _this.$router.push({
              path: 'center',
              params: ''
            })

          } else {
            if (checkMbInfo["verify_mobile"]
              === enumerations.verifyMobile.yes.key) {
              _this.verifyMobile = true
            } else {
              _this.verifyMobile = false
            }
          }
        } else {

          const errorInfo = error[result["code"]]

          if (common.isEmptyObject(errorInfo)) {
            _this.showToast = true
            _this.toastType = 'cancel'
            _this.toastText = result["msg"]
          } else {
            _this.$router.push(errorInfo)
          }

        }

      }

    },
    methods: {
      getCode: function () {
        const _this = this

        const ajax = this.$http.create({
          headers: {'content-type': 'application/x-www-form-urlencoded'}
        })

        if (!common.checkMobile(this.mobile)) {
          this.showToast = true
          this.toastText = '请填写正确的手机号'
        } else {

          this.showLoading = true

          const data = {
            openid: this.openid,
            mobile: this.mobile,
            mchCode: this.cacheMchCode
          }

          console.log('data=' + data)
          ajax.post(this.$apiRoute.sendMobileCode, this.$qs.stringify(data))
            .then(function (response) {
              _this.showLoading = false
              const result = response
              if (result.data.code === 200) {
                _this.getCodeBtnText = 60
                const end = 0

                //倒计时
                setInterval(function () {
                  if (_this.getCodeBtnText > end) {
                    _this.showGetCodeBtn = false
                    _this.getCodeBtnText--
                  } else {
                    _this.showGetCodeBtn = true
                  }
                }, 1000)

                _this.showToast = true
                _this.toastType = 'success'
                _this.toastText = '短信发送成功'
              } else {
                _this.showToast = true
                _this.toastType = 'cancel'
                _this.toastText = response.data.msg
              }
            })
        }
      },

      register: function () {

        const _this = this
        const ajax = this.$http.create({
          headers: {'content-type': 'application/x-www-form-urlencoded'}
        })

        if (common.isEmptyString(this.username)) {
          this.showToast = true
          this.toastType = 'cancel'
          this.toastText = '姓名不能为空'
        } else if (!common.checkMobile(this.mobile)) {
          this.showToast = true
          this.toastText = '请填写正确的手机号'
        } else {

          this.showLoading = true
          const data = {
            openid: this.openid,
            mobile: this.mobile,
            username: this.username,
            gender: this.sexId,
            birthday: this.birthday,
            code: this.code,
            mchCode: this.cacheMchCode
          }

          ajax.post(this.$apiRoute.register, this.$qs.stringify(data))
            .then(function (response) {
              _this.showLoading = false

              if (response.data.code === 200) {
                if (response.data.values.need_next) {
                  //微信添加卡券
                  wx.addCard({
                    cardList: [{
                      cardId: response.data.values.card_id,
                      cardExt: response.data.values.card_ext
                    }], // 需要添加的卡券列表
                    success: function (res) {

                      const callBackData = {
                        openid: _this.openid,
                        mchCode: _this.cacheMchCode,
                        cardNo: ''
                      }

                      ajax.post(_this.$apiRoute.addWechatMemberCard, _this.$qs.stringify(callBackData))
                        .then(function (response) {
                          _this.showLoading = false
                          if (response.data.code === 200) {
                            _this.$router.push({
                              path: 'center',
                              params: ''
                            })
                          }
                        })
                    },
                    cancel: function (res) {
                      _this.$router.push({
                        path: 'center',
                        params: ''
                      })
                    },
                    fail: function (res) {
                      _this.$router.push({
                        path: 'center',
                        params: ''
                      })
                    }
                  });
                }
              } else {
                if (response.data.code === 10011) {
                  _this.showAlert = true
                  _this.alertText = response.data.msg
                  _this.alertBtn = '绑定会员'
                } else {
                  _this.showAlert = true
                  _this.alertText = response.data.msg
                }
              }
            })
        }
      },

      cancelAlert: function () {
        this.showAlert = false
      },

      hideAlert: function () {
        this.showAlert = false
      },

      bindMember: function () {
        this.$router.push({
          name: 'bindMember',
          params: {'mobile': this.mobile}
        })
      }
    }
  }
</script>
<style scoped>
  @import "./../assets/css/register.css";
  @import "~weui";
</style>
